package com.my.blog.myblog.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.blog.myblog.entity.Links;
import com.my.blog.myblog.service.LinksService;
import com.my.blog.utils.ResultBean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/***
 *
 * @Auther: MuYun
 * @Date: 2021/8/23 10:35
 * @Description： 友链的controller
 *
 */
@RestController
public class LinksController {

    @Resource
    private LinksService linksService;

    /**
     * 查询友链
     * @return
     */
    @GetMapping("/selectAllLinks")
    public ResultBean<List<Links>> selectAllLinks(){
        QueryWrapper<Links> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(Links::getStatus,"1").eq(Links::getIsApply,"1");
        List<Links> linksList = linksService.list(wrapper);
        ResultBean<List<Links>> resultBean=new ResultBean<>();
        if(linksList.size()==0){
            resultBean.setMsg("暂无友链");
        }else {
            resultBean.setData(linksList);
        }
        return resultBean;
    }

    /**
     * 新增友链
     * @param links
     * @return
     */
    @PostMapping("/addLinks")
    public ResultBean<Object> addLinks(Links links){
        System.out.println(links);
        links.setAddTime(LocalDateTime.now());
        ResultBean<Object> resultBean=new ResultBean<>();
        if(linksService.save(links)){
            resultBean.setMsg("添加成功0.0");
        }else {
            resultBean.setCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 根据点击更新clickNum
     * @param id
     * @return
     */
    @PostMapping("/selectLinksById")
    public ResultBean<Object> selectLinksById(@RequestParam(value = "id") Integer id){
        Links links = linksService.getById(id);
        ResultBean<Object> resultBean=new ResultBean<>();
        if(ObjectUtil.isNotEmpty(links)){
            links.setClicknum(links.getClicknum()+1);
            linksService.updateById(links);
        }else {
            resultBean.setCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
